package com.vsu.bookstore.mvc.ui.widgets;

import java.text.DecimalFormat;
import java.util.Collection;
import java.util.Iterator;

import com.vaadin.data.Container;
import com.vaadin.data.util.BeanItemContainer;
import com.vaadin.ui.Component;
import com.vaadin.ui.DefaultFieldFactory;
import com.vaadin.ui.Field;
import com.vaadin.ui.Table;
import com.vsu.bookstore.mvc.model.bean.BookStoreItem;
import com.vsu.bookstore.mvc.ui.widget.fields.CustomTextField;
import com.vsu.bookstore.util.CurrencyExchangeProvider;

@SuppressWarnings("serial")
public class CheckoutTable extends Table
{
  private static class CheckoutTableFieldFactory extends DefaultFieldFactory
  {
    public CheckoutTableFieldFactory()
    {
    }

    @Override
    public Field createField(final Container container, final Object itemId,
        final Object propertyId, final Component uiContext)
    {
      final Field result = new CustomTextField();
      result.setReadOnly(true);

      if (propertyId.equals("title"))
      {
        result.addStyleName("alignleft");
        result.addStyleName("bold");
      }
      else
        result.addStyleName("alignright");
      return result;
    }
  }

  public CheckoutTable(final Container container)
  {
    super();
    addStyleName("checkout");
    setWidth("100%");
    setPageLength(4);
    setContainerDataSource(container);
    setVisibleColumns(new Object[]
    { "title", "quantity", "priceInRubles" });
    setColumnHeaders(new String[]
    { "Title", "Quantity", "Price" });
    setColumnAlignments(new String[]
    { Table.ALIGN_LEFT, Table.ALIGN_RIGHT, Table.ALIGN_RIGHT });
    setColumnExpandRatio("title", 1);
    setFooterVisible(true);
    updatePriceFooter();
    setColumnFooter("title", "Total Price:");
    setEditable(true);
    setTableFieldFactory(new CheckoutTableFieldFactory());
  }

  @SuppressWarnings("unchecked")
  public void updatePriceFooter()
  {
    final BeanItemContainer<BookStoreItem> container =
      (BeanItemContainer<BookStoreItem>) getContainerDataSource();
    Double result = 0d;
    final Collection<BookStoreItem> ids = container.getItemIds();
    final Iterator<BookStoreItem> it = ids.iterator();
    while (it.hasNext())
    {
      final BookStoreItem item = it.next();
      result += item.getPrice() * item.getQuantity();
    }
    final DecimalFormat format = new DecimalFormat();
    format.setMaximumFractionDigits(2);
    setColumnFooter("priceInRubles", "" + format.format(result * CurrencyExchangeProvider.getEuroToRubleRatio()) + " RUB");
  }
}
